#!/usr/bin/python

# Copyright 2009, Fei Yu, feiyu [at] berkeley [dot] edu

# This file is part of Topics-Portal.
#
# Topics-Portal is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Topics-Portal is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with PyGrams.  If not, see <http://www.gnu.org/licenses/>.

from django import template
#from urllib import quote, urlopen, urlencode
from django.conf import settings
import json
import random
import requests

register = template.Library()

CLOUD_SIZE = 40


def make_tags(topics):
    for topic in topics:
        si = random.random() #si = size indicator
        yield u'<div class="%(size)s"><a href="/%(url)s">%(name)s</a></div>' % {
            'size': (u' small' if si < .1 else
                     u'' if si < .5 else
                     u' big' if si < .85 else
                     u' verybig'),
             'url': 'topics/' + topic['_id'],
#            'url': topic['id'],
            'name': topic['name']}


@register.simple_tag
def topics_cloud():
#	query_head = "http://localhost:5984/sti/_design/lucene2/_view/topicIndex"
    headers = {'content-type': 'application/json'}
    query_head = settings.BIBSERVER_HOST + settings.BIBSERVER_DATABASE_NAME + '/_search'
    query = {
        "size": CLOUD_SIZE, 
        "query": {
            "custom_score": {    
                "query": {
                    "bool" : {
                        "should": [
                            {"term": { "type": "topic"}}, 
                            {"term": {"collection":"statopic"}}
                        ]
                    }
                },
                "script": "random()*20"
            }
        },
        "fields": ["_id", "name"]
    }
    resp = requests.post(query_head, data=json.dumps(query), headers=headers)
    selected_topics = [topic['fields'] for topic in resp.json['hits']['hits']]
#	TOPICS_TOTAL = simplejson.load(urlopen(query_head + \
#					"?limit=1"))['total_rows']
#	samples = sorted(random.sample(range(TOPICS_TOTAL), CLOUD_SIZE))
#	selected_topics = []
#	prev = 0
#	startkey = None
#	for i in range(CLOUD_SIZE):
#		difference = samples[i] - prev
#		if startkey:
#			value = simplejson.load(urlopen(query_head +'?'+ \
#					urlencode({"limit":1,"startkey":'"' + startkey + '"',
#						"skip":difference }, '&')))['rows'][0]['value']
#		else:
#			value = simplejson.load(urlopen(query_head +'?' + \
#					urlencode({"limit":1,"skip":difference },\
#					'&')))['rows'][0]['value']
#		startkey = value['id']
#		prev = samples[i]	
#		selected_topics.append(value)		
#	random.shuffle(selected_topics)
    return u'\n'.join(make_tags(selected_topics))
